package tenant

import (
	"context"
	constants2 "git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/common"
	"gorm.io/gorm"
	"time"
)

type TenantsInstanceRepository struct {
	common.TenantServiceDB
}

func NewTenantsInstanceRepository() TenantsInstanceRepositoryIface {
	return &TenantsInstanceRepository{}
}

func (g *TenantsInstanceRepository) AddTenantsInstance(ctx context.Context, data *TenantsInstance) (int32, error) {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantServiceDB(ctx).Create(&data).Error
	if err != nil {
		return 0, err
	}
	return data.Id, nil
}

func (g *TenantsInstanceRepository) SaveTenantsInstance(ctx context.Context, data *TenantsInstance) error {
	data.ModifiedOn = time.Now()
	err := g.GetTenantServiceDB(ctx).Save(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *TenantsInstanceRepository) GetTenantsInstance(ctx context.Context, tenantCode string) (*TenantsInstance, error) {
	tenantsInstance := &TenantsInstance{}
	err := g.GetTenantServiceDB(ctx).
		Table(TenantsInstance{}.TableName()).
		Where("is_deleted = ?", constants2.IsDeletedFalse).
		Where("tenant_code = ?", tenantCode).
		Order("created_on desc").First(tenantsInstance).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return tenantsInstance, err
	}
	return tenantsInstance, nil
}
